import { defineEventHandler, readBody } from "h3";
import { validateUser } from "../../database/services/userService";
import { generateToken } from "../../utils/jwt";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);

    // 数据验证
    if (!body.username || !body.password) {
      throw new Error("用户名和密码不能为空");
    }

    // 验证用户
    const user = await validateUser(body.username, body.password);

    if (!user) {
      return {
        success: false,
        error: "用户名或密码错误",
      };
    }

    // 生成JWT token
    const token = generateToken(user.id, user.username);

    return {
      success: true,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        name: user.name,
        authority: user.authority,
      },
      token,
    };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
});
